﻿using System;
using System.Web.UI.HtmlControls;
using ITViet.Web.App_Code;
using ITViet.Services;
using ITViet.Domains;

namespace ITViet.Web.Admin
{
  public partial class PhotoList : AdminBasePage
  {
    #region Properties
    internal override int RequiredPermission
    {
      get
      {
        return (int)FunctionList.Album;
      }
    }

    internal override void SetPermission()
    {
      if (!CanModify) btnAdd.Visible = false;
      if (!CanDelete) btnDelete.Visible = false;
    }

    private string m_innerError = string.Empty;
    private string m_checkBoxList = string.Empty;
    private string m_allIdList = string.Empty;

    private int AlbumId
    {
      get
      {
        int albumId = 0;
        if (Request.QueryString["albumId"] != null)
          int.TryParse(Request.QueryString["albumId"], out albumId);
        return albumId;
      }
    }

    private string MediaType
    {
      get
      {
        string type = Request.QueryString["type"];
        if (type == MultimediaType.Intro)
        {
          return MultimediaType.Intro;
        }
        else
        {
          return MultimediaType.Banner;
        }
      }
    }
    #endregion

    #region Methods
    private void SettingUpload()
    {
      MultiUpload1.FileType = AllowFileContentType.Image;
      MultiUpload1.UploadCompleteFunction = "UploadComplete";
      MultiUpload1.UploadSessionName = SessionName.UploadContainPostedFile;
      MultiUpload1.UploadFolder = FolderDirector.Photo;
      MultiUpload1.NoticeMessage = Resources.Messages.ERR0024;

      if (Session[SessionName.PhotoBackLink] != null)
      {
        hfBackTo.Value = Session[SessionName.PhotoBackLink].ToString();
      }
      else
      {
        hfBackTo.Value = "PhotoAlbums.aspx";
      }
    }

    private void LoadPhoto()
    {
      MultimediaService service = new MultimediaService();
      TList<Multimedia> pList = new TList<Multimedia>();
      if (AlbumId > 0)
      {
        pList = service.GetByAlbumId(AlbumId);
        lblNote.Text = "(*) " + Resources.Strings.ImgSizePhoto;
      }
      else
      {
        pList = service.GetPhotoByType(MediaType);
        lblNote.Text = "(*) " + Resources.Strings.ImgSizeBanner;
      }

      foreach (Multimedia photo in pList)
      {
        if (!string.IsNullOrEmpty(photo.Path))
        {
          photo.Path = "../" + photo.Path;
        }
      }

      dvList.DataSource = pList;
      dvList.DataBind();
    }

    private string SavePhoto()
    {
      try
      {
        MultimediaService pService = new MultimediaService();
        TList<Multimedia> pList = new TList<Multimedia>();
        string uploadedList = string.Empty;
        if (Session[SessionName.UploadReturnFiles] != null)
          uploadedList = Session[SessionName.UploadReturnFiles].ToString();

        if (!string.IsNullOrEmpty(uploadedList))
        {
          string[] fileList = uploadedList.Split(';');
          for (int i = 0; i < fileList.Length; i++)
          {
            if (string.IsNullOrEmpty(fileList[i]))
              continue;
            Multimedia photo = new Multimedia();
            photo.Path = fileList[i];
            photo.PostedBy = CurrentUser.Username;
            photo.PostedDate = DateTime.Now;
            if (AlbumId == 0)
            {
              photo.AlbumId = null;
              photo.Type = MediaType;
            }
            else
            {
              photo.AlbumId = AlbumId;
              photo.Type = MultimediaType.Photo;
            }

            photo.Status = VisibleStatus.Active;
            pList.Add(photo);
          }
        }

        ClearSession(new string[] { SessionName.UploadReturnFiles, SessionName.UploadContainPostedFile });
        if (pList.Count > 0)
        {
          pService.Save(pList);

          return "SaveOK|";
        }
      }
      catch (Exception ex)
      {
        WriteLog("PhotoList.aspx::Save Photo", ex);
        return Resources.Messages.ERR0004;
      }
      return string.Empty;
    }

    private string DeletePhoto(string deletedList)
    {
      try
      {
        if (!string.IsNullOrEmpty(deletedList))
        {
          MultimediaService pService = new MultimediaService();
          if (deletedList.EndsWith(","))
            deletedList = deletedList.Remove(deletedList.Length - 1);
          string[] idList = deletedList.Split(',');
          string[] imagePath = new string[idList.Length];
          for (int i = 0; i < idList.Length; i++)
          {
            if (string.IsNullOrEmpty(idList[i]))
              continue;
            int id = 0;
            int.TryParse(idList[i], out id);
            Domains.Multimedia photo = pService.GetById(id);
            if (photo != null)
            {
              string filePath = @MapPath("~\\" + photo.Path);
              imagePath[i] = filePath;
            }
          }

          pService.DeleteByIdList(deletedList);
        }
      }
      catch (Exception ex)
      {
        WriteLog("PhotoList.aspx::Delete Photo", ex);
        return Resources.Messages.ERR0004;
      }
      return "DeleteOK|";
    }
    #endregion

    #region Events
    protected void Page_Load(object sender, EventArgs e)
    {
      SettingUpload();
      if (!IsCallback && !IsPostBack)
      {
        if (AlbumId == 0)
        {
          btnBackTo.Visible = false;
        }

        LoadPhoto();
      }
      if (dvList.IsCallback)
      {
        LoadPhoto();
      }
    }

    protected void dvList_CustomCallback(object source, DevExpress.Web.ASPxClasses.CallbackEventArgsBase e)
    {
      string[] para = e.Parameter.Split('|');
      switch (para[0])
      {
        case "Save":
          m_innerError = SavePhoto();
          break;
        case "Delete":
          m_innerError = DeletePhoto(para[1]);
          break;
      }
      LoadPhoto();
      if (m_innerError.Contains("OK"))
      {
        m_innerError += m_checkBoxList + "|" + m_allIdList;
      }
    }

    protected void dvList_CustomJSProperties(object sender, DevExpress.Web.ASPxClasses.CustomJSPropertiesEventArgs e)
    {
      e.Properties["cpInnerError"] = m_innerError;
    }

    protected void dvList_DataBound(object sender, EventArgs e)
    {
      if (dvList.DataSource == null) return;
      hfCheckBoxList.Value = string.Empty;
      hfAllIdList.Value = string.Empty;
      m_allIdList = string.Empty;
      m_checkBoxList = string.Empty;
      for (int i = 0; i < dvList.Items.Count; i++)
      {
        HtmlInputCheckBox ckbox = dvList.FindItemControl("item_checkbox", dvList.Items[i]) as HtmlInputCheckBox;
        if (ckbox != null)
        {
          Domains.Multimedia photo = dvList.Items[i].DataItem as Domains.Multimedia;
          if (photo != null)
          {
            ckbox.Attributes.Add("onclick", "onSelect('" + photo.Id + "', this.checked)");
            hfAllIdList.Value += photo.Id + ",";
            m_allIdList += photo.Id + ",";
          }

          hfCheckBoxList.Value += ckbox.ClientID + ",";
          m_checkBoxList += ckbox.ClientID + ",";
        }
      }
    }
    #endregion
  }
}
